import * as vscode from "vscode"
const md5 = require("md5")
const axios = require("axios")
interface dst {
  dst: string
}
interface baidu {
  trans_result: Array<dst>
  error_code?: string
}
// 请求百度翻译函数
const translate = async (q: string, from: string, to: string) => {
  const appid = "20210929000959942"
  const secret = "j3STJyEEXF6YmTCKZMdM"
  const salt = Math.random()
  const { data }: { data: baidu } = await axios({
    method: "get",
    url: "https://fanyi-api.baidu.com/api/trans/vip/translate",
    params: {
      from,
      to,
      appid,
      q,
      salt,
      sign: md5(appid + q + salt + secret)
    }
  })
  if (data.error_code == "54003") {
    vscode.window.showErrorMessage("请求过于频繁，请控制在1s请求一次")
    return ""
  }
  const { dst } = data.trans_result[0]
  // 转换驼峰
  const result = dst
    .split(" ")
    .map((v: string, i: number) => {
      return i !== 0 ? v.charAt(0).toLocaleUpperCase() + v.slice(1) : v.toLocaleLowerCase()
    })
    .join("")
  // 去除标题符号
  return result.replace(/[.,;':]/g, "")
}
// 拆入字符至字符串指定位置
function insertStr(soure: string, start: number, newStr: string) {
  return soure.slice(0, start) + newStr + soure.slice(start)
}
// 判断字符串是否全为中文
function isChinese(temp: string) {
  return /[^\u4e00-\u9fa5]/.test(temp) ? false : true
}
export function activate(context: vscode.ExtensionContext) {
  let disposable = vscode.commands.registerCommand("test.Hello VS Code", async () => {
    const { activeTextEditor } = vscode.window // 获取当前聚焦的文本编辑器
    // activeTextEditor!.selection 当前选中的范围
    const currentSelect = activeTextEditor!.document.getText(activeTextEditor!.selection) // 根据范围获取选中文本
    // 已选择文本 并且是纯中文字符串
    if (currentSelect && isChinese(currentSelect)) {
      const result = await translate(currentSelect, "zh", "en")
      activeTextEditor!.edit(editBuilder => {
        editBuilder.replace(activeTextEditor!.selection, result)
      })
    } else {
      let txt = activeTextEditor!.document.lineAt(activeTextEditor!.selection.active.line).text //获取光标所在行的文本
      const cnNumber = txt.search(/[\u4e00-\u9fa5]/g) // 获取第一个中文的位置
      const cn = txt!.match(/[\u4e00-\u9fa5]/g) // 提取字符串中的中文
      // 如果存在中文拼接成字符串
      if (cn) {
        let result = await translate(cn.join(""), "zh", "en")
        txt = txt.replace(/[\u4e00-\u9fa5]/g, "") // 去除当前行的中文
        result = insertStr(txt, cnNumber, result) // 拆入中文翻译成的英文
        activeTextEditor!.edit(editBuilder => {
          editBuilder.replace(new vscode.Range(new vscode.Position(activeTextEditor!.selection.start.line, 0), new vscode.Position(activeTextEditor!.selection.end.line, activeTextEditor!.selection.end.character)), result)
        })
        return
      }
      vscode.window.showInformationMessage("未检测到当前行或选中处的中文文本")
    }
    vscode.languages.registerHoverProvider("*", {
      provideHover: async (document, position) => {
        const word = document.getText(document.getWordRangeAtPosition(position))
        const result = await translate(word, "en", "zh")
        return new vscode.Hover("中文:" + result)
      }
    })
  })

  context.subscriptions.push(disposable)
}
export function deactivate() {}
